package xyz.honeysuccess.service.Impl;

import cn.hutool.core.lang.UUID;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import xyz.honeysuccess.entity.FileData;
import xyz.honeysuccess.mapper.FileDataMapper;
import xyz.honeysuccess.service.FileDataService;
import xyz.honeysuccess.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Honey
 * @date 2021/12/21
 */
@Service
public class FileDataServiceImpl implements FileDataService {

    @Resource
    private FileDataMapper fileDataMapper;

    /**
     * 文件存储地址
     */
    public static final String DOWNLOAD = "D:\\honeyFile\\";

    private static final Map<String, String> MimeType = new HashMap<String, String>(){{
        put("jpeg", "image/jpeg");
        put("txt", "text/html");
    }};

    @Override
    public String saveFileData(MultipartFile file) throws IOException {
        FileData fileData = new FileData();
        // 生成UUID
        String uuid = UUID.randomUUID().toString();
        // 生成当前日期
        String date = DateUtil.getDate();
        // 文件数据输入流
        InputStream inputStream = file.getInputStream();
        // 文件保存地址
        String address = DOWNLOAD + date ;
        // 获得文件名
        String oldName = file.getOriginalFilename();
        // 存入服务器的文件名
        String fileName = uuid + oldName.substring(oldName.lastIndexOf("."));
        // 设置文件元数据
        fileData.setId(uuid);
        fileData.setOldName(oldName);
        fileData.setType(oldName.substring(oldName.lastIndexOf('.') + 1));
        fileData.setSize(file.getSize());
        fileData.setAddress(address);
        fileData.setCreateTime(new Date());
        // 把文件存在指定目录下
        setFile(address + "\\" + fileName, inputStream);
        // 插入文件的元数据
        fileDataMapper.insertSelective(fileData);
        return uuid;
    }

    @Override
    public FileData getFileDateByUUID(String uuid) {
        return fileDataMapper.selectByPrimaryKey(uuid);
    }

    @Override
    public Map<String, Object> downloadFile(String uuid, HttpServletResponse response) {
        // map返回信息
        Map<String, Object> map = new HashMap<>(8);
        //从数据库中获取文件元数据
        FileData fileData = getFileDateByUUID(uuid);
        if(fileData == null){
            map.put("message", "不存在该文件！");
            map.put("code", "410");
            return map;
        }
        // 拼接文件名
        String filename = uuid + "." + fileData.getType();
        // 拼接路径
        String filePath = fileData.getAddress()+ "\\" + filename;
        // 设置返回的ContentType  CharacterEncoding
        response.setContentType(MimeType.get(fileData.getType()));
        response.setCharacterEncoding("UTF-8");
        // 读取路径下面的文件
        try {
            // 将文件写入response
            FileCopyUtils.copy(new FileInputStream(filePath), response.getOutputStream());
        } catch (IOException e) {
            map.put("message", "下载失败");
            map.put("code", "410");
            return map;
        }
        return null;
    }


    public void setFile(String path, InputStream inputStream) throws IOException {
        // 创建一个文件数据流
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        File file = new File(path);
        // 不存在该目录，去创建该目录
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        // 把文件存在服务器的文件夹里
        OutputStream out = new FileOutputStream(file);
        int size = 0;
        byte[] buf = new byte[1024];
        while ((size = bis.read(buf)) != -1) {
            out.write(buf, 0, size);
        }
        bis.close();
        out.close();
    }
}
